﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using MVCAppToolkit;
using NuPattern.Diagnostics;
using NuPattern.Runtime;
using NuPattern.Runtime.ToolkitInterface;

namespace SearchFormToolkit.Automation.TypeConverters
{
    /// <summary>
    /// A custom type converter for returning a list of System.String values.
    /// </summary>
    [DisplayName("View Model Type Converter")]
    [Category("MVC Applications")]
    [Description("Returns a list of the configured View Models in the application.")]
    [CLSCompliant(false)]
    public class ViewModelTypeConverter : StringConverter
    {
        private static readonly ITracer tracer = Tracer.Get<ViewModelTypeConverter>();

        /// <summary>
        /// Determines whether this converter supports standard values.
        /// </summary>
        public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
        {
            return true;
        }

        /// <summary>
        /// Determines whether this converter only allows selection of items returned by <see cref="GetStandardValues"/>.
        /// </summary>
        public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
        {
            return true;
        }

        /// <summary>
        /// Returns the list of string values for the enumeration
        /// </summary>
        public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
        {
            var items = new List<string>();

            // Get the current element the converter is configured upon
            var currentElement = context.Instance as IProductElement;
            if (currentElement != null)
            {
                // Get the search provider for the search form
                var searchProvider = currentElement.As<ISearchProvider>();
                if (searchProvider != null)
                {
                    // Add the currently configured ViewModels
                    var viewModels = searchProvider.AsElement().Root.As<IMvcApplication>().DefaultView.ViewModels;
                    foreach (var viewModel in viewModels.ViewModel)
                    {
                        items.Add(viewModel.CodeIdentifier);
                    }
                }
            }

            return new StandardValuesCollection(items);
        }
    }
}
